import envConfig from '@/config/index'

enum RequestMethod {
  GET = 'GET',
  POST = 'POST',
  PUT = 'PUT',
  DELETE = 'DELETE'
}

interface Result<T> extends WechatMiniprogram.IAnyObject {
  code: number
  data: T
  msg: string
}

function request<T>(
  url: string,
  method: RequestMethod,
  data: any,
  config?: WechatMiniprogram.RequestOption
): Promise<Result<T>> {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${envConfig.baseUrl}/${url}`,
      method,
      data,
      header: {
        Authorization: wx.getStorageSync('token') || ''
      },
      ...config,
      success(res: WechatMiniprogram.RequestSuccessCallbackResult<Result<T>>) {
        const { code } = res.data
        switch (code) {
          case 401:
            wx.clearStorageSync()
            wx.reLaunch({ url: '/pages/login/index' })
            reject(res.data)
            break
          case 403:
            reject(res.data)
            wx.$toast('没有权限')
            break
          case 500:
            wx.$toast(res.data.msg)
            reject(res.data)
            break
          default:
            resolve(res.data)
            break
        }
      },
      fail(err) {
        wx.$toast('系统繁忙')
        reject(err)
      }
    })
  })
}

const get = <T = any>(
  url: string,
  data?: any,
  config?: WechatMiniprogram.RequestOption
) => request<T>(url, RequestMethod.GET, data, config)
const post = <T = any>(
  url: string,
  data?: any,
  config?: WechatMiniprogram.RequestOption
) => request<T>(url, RequestMethod.POST, data, config)
const put = <T = any>(
  url: string,
  data?: any,
  config?: WechatMiniprogram.RequestOption
) => request<T>(url, RequestMethod.PUT, data, config)
const del = <T = any>(
  url: string,
  data?: any,
  config?: WechatMiniprogram.RequestOption
) => request<T>(url, RequestMethod.DELETE, data, config)

export default {
  get,
  post,
  put,
  del
}
